<?php

/**
 * content actions.
 *
 * @package    ems1
 * @subpackage content
 * @author     Jacobo Martínez
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class contentActions extends sfActions
{
    public function executeIndex(sfWebRequest $request)
    {
        $this->ems_contents = $this->getRoute()->getObjects();
    }

    public function executeShow(sfWebRequest $request)
    {
        $content = $this->getRoute()->getObject();

        return $this->renderPartial('show'.$content->getType()->getType(), array('content' => $content));
    }

    public function executeNew(sfWebRequest $request)
    {
        $section = $this->getRoute()->getObject();
        $content = new EmsContent();
        $content->setSection($section);

        switch ($section->getType()->getType()) {
            case 'News':
                $content_type = $section->getNewsSection()->getContentType();
                break;
            case 'Gallery':
                $content_type = $section->getGallerySection()->getContentType();
                break;
            case 'Download':
                $content_type = $section->getDownloadSection()->getContentType();
                break;
            default:
                break;
        }

        $content->setType($content_type);

        $form = new EmsContentForm($content, array('portal_id' => $section->getPortalId()));

        return $this->renderPartial('form'.$content->getType()->getType(), array('form' => $form));
    }

    public function executeCreate(sfWebRequest $request)
    {
        $section = $this->getRoute()->getObject();
        $content = new EmsContent();
        $content->setSection($section);

        switch ($section->getType()->getType()) {
            case 'News':
                $content_type = $section->getNewsSection()->getContentType();
                break;
            case 'Gallery':
                $content_type = $section->getGallerySection()->getContentType();
                break;
            case 'Download':
                $content_type = $section->getDownloadSection()->getContentType();
                break;
            default:
                break;
        }

        $content->setType($content_type);

        $form = new EmsContentForm($content, array('portal_id' => $section->getPortalId(),));

        $valid = $this->processForm($request, $form);

        if(!$valid){
            return $this->renderPartial('form'.$content->getType()->getType(), array('form' => $form, 'valid' => $valid ));
        } else {
            return sfView::NONE;
        }
    }

    public function executeEdit(sfWebRequest $request)
    {
        $content = $this->getRoute()->getObject();
        
        $form = new EmsContentForm($content, array('portal_id' => $content->getSection()->getPortalId()));

        return $this->renderPartial('form'.$content->getType()->getType(), array('form' => $form));
    }

    public function executeUpdate(sfWebRequest $request)
    {
        $content = $this->getRoute()->getObject();

        $form = new EmsContentForm($content, array('portal_id' => $content->getSection()->getPortalId()));

        $valid = $this->processForm($request, $form);

        if(!$valid){
            return $this->renderPartial('form'.$content->getType()->getType(), array('form' => $form));
        } else {
            return sfView::NONE;
        }
    }

//  public function executeDelete(sfWebRequest $request)
//  {
//    $request->checkCSRFProtection();
//
//    $this->getRoute()->getObject()->delete();
//
//    $this->redirect('content/index');
//  }

    protected function processForm(sfWebRequest $request, sfForm $form)
    {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        $valid = $form->isValid();
        if ($valid){
            $audit = new EmsAudit();

            if($form->getObject()->isNew()){
                $audit->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Crear contenido'));
            } else {
                $audit->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Editar contenido'));
            }

            $content = $form->save();

            Util::emptyDir(sfConfig::get('sf_upload_dir').'/portal_'.$content->getSection()->getPortalId().'/temp_files/');

            $user = $this->getUser()->getGuardUser();

            $audit->setPortal($content->getSection()->getPortal());
            $audit->setUser($user);
            $audit->setObjectId($content->getId());

            $audit->save();
            
            return $this->renderPartial('multiUpdate', array('content' => $content, 'section' => $content->getSection()));
        }
        return $valid;
    }

    public function executeMultiupdate(sfWebRequest $request)
    {
        $section = $this->getRoute()->getObject();

        return $this->renderPartial('multiUpdate', array('section' => $section));
    }

    public function  executeListComments(sfWebRequest $request)
    {
        $content = $this->getRoute()->getObject();

        $pager = new sfDoctrinePager('EmsContent', 10);
        $pager->setQuery($content->getEnabledCommentsQuery());
        $pager->setPage($request->getParameter('page', 1));
        $pager->init();

        $form = new CommenstForApprovalContainerForm($pager->getResults());

        if ($request->isMethod(sfRequest::PUT)) {
            if($this->proccessCommentsApproval($request, $form)){
                $page = $request->getParameter('page', 1);

                $next = $request->getParameter('next', 1);

                if($page == $next){
                    $pager->setPage($pager->getFirstPage());
                } else {
                    $pager->setPage($next);
                }

                $pager->init();

                $form = new CommenstForApprovalContainerForm($pager->getResults());
            }
        }
        return $this->renderPartial('commentList', array('content' => $content,'pager' => $pager, 'form' => $form));
    }

    protected function proccessCommentsApproval(sfWebRequest $request, sfForm $form)
    {
        $form->bind($request->getParameter($form->getName()));

        $valid = $form->isValid();

        if ($valid){
            $form->save();
        }

        return $valid;
    }

    public function executeTempFileUpload(sfWebRequest $request){

        $content_type = $this->getRoute()->getObject();

        $content = new EmsContent();

        $content->setType($content_type);

        $content->setSectionId($request->getParameter('section_id'));

        $form = new EmsContentForm($content,array('portal_id' => $request->getParameter('portal_id')));

        $files = $request->getFiles($form->getName());

        $json_response = array();

        $file = null;

        $errors = array();
        
        $thumb_type = $request->getParameter('thumb','');

        if(strcmp($thumb_type,'') != 0){
            $file = $files['thumb_'.$thumb_type.'_tmp'];
            if(strcasecmp($thumb_type, 'small') == 0){
                $errors = $this->validateImageFile($file, 40, 40);
            } else if(strcasecmp($thumb_type, 'big') == 0){
                $errors = $this->validateImageFile($file, 100, 100);
            } else {
                $errors['has_errors'] = false;
            }

            if($errors['has_errors']){
                $json_response['valid'] = false;

                $json_response['no_an_image'] = !$errors['is_image'];

                $json_response['no_rigth_width'] = !$errors['valid_width'];

                $json_response['no_rigth_height'] =  !$errors['valid_height'];
            } else {
                $json_response['valid'] = true;

                $json_response['file_name'] = $file['name'];

                $json_response['size'] = $file['size'];

                $json_response['type'] = $file['type'];
                
                $json_response['temp_file'] = Util::saveTempFile($file, $request->getParameter('portal_id'));

                $json_response['portal_id'] = $request->getParameter('portal_id');
            }
            return $this->renderText(json_encode($json_response));
        }

        switch ($content_type->getType()) {
            case 'Image':
                for($i = 0; $i < 30; $i++) {
                    if(isset($files['Image']['Files'][$i]['tmp_file'])){
                        
                        $file = $files['Image']['Files'][$i]['tmp_file'];

                        $image_file = $form->getEmbeddedForm('Image')->getEmbeddedForm('Files')->getEmbeddedForm($i)->getObject();

                        $errors = $this->validateImageFile($file, $image_file->getSize()->getWidth(), $image_file->getSize()->getHeight());

                        if($errors['has_errors']){
                            $json_response['valid'] = false;

                            $json_response['no_an_image'] = !$errors['is_image'];

                            $json_response['no_rigth_width'] = !$errors['valid_width'];

                            $json_response['no_rigth_height'] =  !$errors['valid_height'];
                        } else {
                            $json_response['valid'] = true;

                            $json_response['file_name'] = $file['name'];

                            $json_response['size'] = $file['size'];
                            
                            $json_response['type'] = $file['type'];

                            $json_response['temp_file'] = Util::saveTempFile($file, $request->getParameter('portal_id'));

                            $json_response['preview'] = Util::resizeImage($json_response['temp_file'], 100, 100);

                            $json_response['preview_size'] = filesize(sfConfig::get('sf_upload_dir').
                                                                '/portal_'.$request->getParameter('portal_id').
                                                                '/temp_files/'.$json_response['preview']);

                            $json_response['preview_type'] = filetype(sfConfig::get('sf_upload_dir').
                                                                '/portal_'.$request->getParameter('portal_id').
                                                                '/temp_files/'.$json_response['preview']);;

                            $json_response['portal_id'] = $request->getParameter('portal_id');
                        }
                        break;
                    }
                }
                break;
            case 'Sound':
                if(isset($files['Sound']['tmp_file'])){
                    $validated_file = null;

                    $file = $files['Sound']['tmp_file'];

                    $validator = new sfValidatorFile(
                                        array(
                                            'required'   => true,
                                            'max_size'   => '1048576',
                                            'path'       => sfConfig::get('sf_upload_dir').'/portal_'.$request->getParameter('portal_id').'/temp_files/',
                                            'mime_types' => array('audio/mpeg', 'audio/mp3', 'audio/x-mp3'),
                                        ), array(
                                            'required'   => 'Debe indicar el archivo de formato mp3 a ser cargado.',
                                            'max_size'   => 'El archivo excede el tamaño máximo permitido, 1MB.',
                                            'mime_types' => 'Tipo de archivo invalido (%mime_type%), el archivo a cargar debe ser de tipo mp3'
                                        ));
                    
                    try {

                        $validator->clean($file);

                    } catch (sfValidatorError $e) {

                        $json_response['valid'] = false;

                        $json_response['error_message'] = $e->getMessage();

                        return $this->renderText(json_encode($json_response));
                    }

                    $json_response['valid'] = true;

                    $json_response['file_name'] = $file['name'];

                    $json_response['temp_file'] = Util::saveTempFile($file, $request->getParameter('portal_id'));

                    $json_response['size'] = $file['size'];

                    $json_response['type'] = $file['type'];

                    $json_response['portal_id'] = $request->getParameter('portal_id');
                }
                break;
            case 'Video':
                if(isset($files['Video']['tmp_file'])){
                    $validated_file = null;

                    $file = $files['Video']['tmp_file'];

                    $validator = new sfValidatorFile(
                                        array(
                                            'required'   => true,
                                            'max_size'   => '1048576',
                                            'path'       => sfConfig::get('sf_upload_dir').'/portal_'.$request->getParameter('portal_id').'/temp_files/',
                                            
                                        ), array(
                                            'required'   => 'Debe indicar el archivo de formato mp4 o 3gp a ser cargado.',
                                            'max_size'   => 'El archivo excede el tamaño máximo permitido, 1 MB.',
                                            'mime_types' => 'Tipo de archivo invalido (%mime_type%), el archivo a cargar debe ser de tipo mp4 o 3gp'
                                        ));

                    try {

                        $validator->clean($file);

                    } catch (sfValidatorError $e) {

                        $json_response['valid'] = false;

                        $json_response['error_message'] = $e->getMessage();

                        return $this->renderText(json_encode($json_response));
                    }

                    $json_response['valid'] = true;

                    $json_response['file_name'] = $file['name'];

                    $json_response['temp_file'] = Util::saveTempFile($file, $request->getParameter('portal_id'));

                    $json_response['size'] = $file['size'];

                    $json_response['type'] = $file['type'];

                    $json_response['portal_id'] = $request->getParameter('portal_id');
                }
                break;
            case 'Article':
                if(isset($files['Article']['tmp_image'])){
                    $validated_image = null;

                    $file = $files['Article']['tmp_image'];

                    $validator = new jsValidatorImage(array(
                                        'mime_types' => array('image/jpeg'),
                                        'trim'       => true,
                                        'path'       => sfConfig::get('sf_upload_dir').'/portal_'.$request->getParameter('portal_id').'/temp_files/',
                                        'required'   => false,
                                        'max_size'   => '1048576',
                                        'minx'       => 1,
                                        'maxx'       => 320,
                                        'miny'       => 1,
                                        'maxy'       => 240
                                    ), array(
                                        'required'   => 'Debe indicar el archivo de formato .JPEG a ser cargado.',
                                        'max_size'   => 'La imagen excede el peso máximo de archivo permitido, 1 MB.',
                                        'mime_types' => 'Tipo de archivo invalido (%mime_type%), el archivo a cargar debe ser de tipo JPEG'
                                    ));

                    try {

                        $validator->clean($file);

                    } catch (sfValidatorError $e) {

                        $json_response['valid'] = false;

                        $json_response['error_message'] = $e->getMessage();

                        return $this->renderText(json_encode($json_response));
                    }

                    $json_response['valid'] = true;

                    $json_response['file_name'] = $file['name'];

                    $json_response['temp_file'] = Util::saveTempFile($file, $request->getParameter('portal_id'));

                    $json_response['size'] = $file['size'];

                    $json_response['type'] = $file['type'];

                    $json_response['portal_id'] = $request->getParameter('portal_id');
                }
                break;
            default:
                break;
        }
        return $this->renderText(json_encode($json_response));
    }

    protected function validateImageFile($file, $width, $height){
        $imagedata = getimagesize($file['tmp_name']);
        
        $errors = array();

        $errors['is_image'] = !$imagedata ? false : true;

        $errors['valid_width'] = $imagedata[0] == $width;

        $errors['valid_height'] = $imagedata[1] == $height;
        
        $errors['has_errors'] = !($errors['is_image'] && $errors['valid_width'] && $errors['valid_height']);

        return $errors;
    }
}
